package com.study.controller;

import com.study.dao.HistoryDao;
import com.study.domain.History;
import com.study.domain.Weather;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class WeatherController {

    HistoryDao historyDao = new HistoryDao();

    //https://blog.csdn.net/wolfies/article/details/78791234
    @RequestMapping("weather")
    public String weather(HttpSession session, Model model) {
        RestTemplate restTemplate = new RestTemplate();
        Weather weather = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/101010100", Weather.class);
        model.addAttribute("weather", weather);
        session.setAttribute("weather", weather);
        return "home";
    }

    @RequestMapping("save")
    public String save(HttpSession session, Model model) {
        Weather weather = (Weather) session.getAttribute("weather");
        historyDao.save(weather, Integer.parseInt(session.getAttribute("userId").toString()));
        //session.removeAttribute("weather");
        model.addAttribute("error", "保存成功");
        return "error";
    }

    @RequestMapping("history")
    public String history(HttpSession session, Integer userId, @RequestParam(defaultValue = "") String date, Model model) {
        if (null == userId || 0 == userId) {
            userId = Integer.parseInt(session.getAttribute("userId").toString());
        }
        List<History> list = historyDao.list(userId, date);
        model.addAttribute("list", list);
        model.addAttribute("userId", userId);
        return "history";
    }

    @RequestMapping("del")
    public String del(Integer id, Model model) {
        historyDao.delById(id);
        model.addAttribute("error", "删除成功");
        return "error";
    }

    @RequestMapping("alter")
    public String alter(Integer id, Model model) {
        History history = historyDao.selectById(id);
        model.addAttribute("history", history);
        return "alter";
    }

    @RequestMapping("update")
    public String update(History history, Model model) {
        historyDao.update(history);
        model.addAttribute("error", "更新成功");
        return "error";
    }

}
